package com.mas.framework.security.core.util;

import com.mas.framework.security.core.pojo.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @author godyao
 * @description 安全服务工具类
 * @date 2023年01月31日21:18
 */
public class SecurityFrameworkUtils {

    public static final String AUTHORIZATION_BEARER = "Bearer";

    /**
     * 从请求中获取对应 header 信息
     * @author godyao
     * @param request 请求
     * @param header 认证 Token 对应的 Header 名字
     * @return java.lang.String 认证 Token
     * @date 2023/1/31 21:18
     */
    public static String obtainAuthorization(HttpServletRequest request, String header) {
        final String authorization = request.getHeader(header);
        if (!StringUtils.hasText(authorization)) {
            return null;
        }
        int index = authorization.indexOf(AUTHORIZATION_BEARER + " ");
        if (index == -1) {
            // 未找到
            return null;
        }
        return authorization.substring(index + 7).trim();

    }

    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 登陆，拿到认证
        final Authentication authentication = buildAuthentication(loginUser, request);
        // 将认证信息设置到上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
